package com.pap.rbac.orgation.agent.impl;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.pap.base.service.impl.PapBaseServiceImpl;
import com.pap.base.util.date.DateUtils;
import com.pap.base.util.string.StringUtilss;
import com.pap.obj.vo.response.ResponseVO;
import com.pap.rbac.agent.orgation.IOrganizationAgent;
import com.pap.rbac.agent.orgation.dto.OrganizationTreeNodeVO;
import com.pap.rbac.orgation.auto.entity.Organization;
import com.pap.rbac.orgation.auto.mapper.OrganizationMapper;

@Transactional
@Service("organizationAgent")
public class OrganizationAgentImpl extends PapBaseServiceImpl<Organization> implements IOrganizationAgent {

	@Autowired
	private OrganizationMapper organizationMapper;
	
	@Override
	public int insertSelectiveList(List<Organization> argList) {
		int returnInt = 0;
		if(argList != null && argList.size() > 0) {
			returnInt = argList.size();
			for(Organization organization : argList) {
				organizationMapper.insertSelective(organization);
			}
		}
		return returnInt;
	}

	@Override
	public List<OrganizationTreeNodeVO> organizationTreeJson(String clientLicenseId, String globalParentId) {
		return organizationMapper.organizationTreeJson(clientLicenseId, globalParentId);
	}

	@Override
	public ResponseVO<Organization> updateAndCheckOrganization(Organization inputOrganization, String loginUserId) {
		// 检验是否循环依赖
		if(checkTreeCircularDependency(inputOrganization.getId(), inputOrganization.getParentId())) {
			// 更新当前的组织机构
			inputOrganization.setModifyIp("0.0.0.0");
			inputOrganization.setModifyTime(DateUtils.getCurrDateTimeStr());
			inputOrganization.setModifyUser(loginUserId);
			
			organizationMapper.updateByPrimaryKeySelective(inputOrganization);
			
			if("-1".equals(inputOrganization.getParentId())) {
				Organization tempForPath = organizationMapper.selectByPrimaryKey(inputOrganization.getId());
				tempForPath.setPathCodes(null);
				tempForPath.setPathIds(null);
				tempForPath.setPathNames(null);
				organizationMapper.updateByPrimaryKey(tempForPath);
			} else {
				Organization tempForPath = organizationMapper.selectByPrimaryKey(inputOrganization.getId());
				Organization tempParentForPath = organizationMapper.selectByPrimaryKey(inputOrganization.getParentId());
				if(StringUtilss.isNotEmpty(tempParentForPath.getPathIds())) {
					tempForPath.setPathIds(tempParentForPath.getPathIds() + "," + tempParentForPath.getId());
        		} else {
        			tempForPath.setPathIds(tempParentForPath.getId());
        		}
        		if(StringUtilss.isNotEmpty(tempParentForPath.getPathCodes())) {
        			tempForPath.setPathCodes(tempParentForPath.getPathCodes() + "," + tempParentForPath.getCode());
        		} else {
        			tempForPath.setPathCodes(tempParentForPath.getCode());
        		}
        		if(StringUtilss.isNotEmpty(tempParentForPath.getPathNames())) {
        			tempForPath.setPathNames(tempParentForPath.getPathNames() + "," + tempParentForPath.getName());
        		} else {
        			tempForPath.setPathNames(tempParentForPath.getName());
        		}
        		organizationMapper.updateByPrimaryKey(tempForPath);
			}
			
			// 维护子集的组织机构
			ResponseVO<Organization> responseVO =  updateRecursionPathColumnOrganization(inputOrganization.getId());
			return responseVO;
		} else {
			return ResponseVO.validfail("组织机构被循环依赖，请检查数据有效性!");
		}
	}
	
	/**
	 * 新维护的组织机构，是否被循环依赖的校验
	 * @param operaOrganizationId
	 * @param newParentOrganizationId
	 * @return
	 */
	@Override
    public Boolean checkTreeCircularDependency(String operaOrganizationId, String newParentOrganizationId) {
    	String parentOrganizationTemp = "";
    	Organization newParentOrganizationInfo = organizationMapper.selectByPrimaryKey(newParentOrganizationId);
    	if(newParentOrganizationInfo != null) {
    		if(StringUtilss.isNotEmpty(newParentOrganizationInfo.getPathIds())) {
    			parentOrganizationTemp = newParentOrganizationInfo.getPathIds() + ",";
    		}
    		parentOrganizationTemp += newParentOrganizationInfo.getId();
    	}
    	if (StringUtilss.checkArrayValue(parentOrganizationTemp.split(","), operaOrganizationId)) {
    		return false;
    	} else {
    		return true;
    	}
    }

	@Override
	public ResponseVO<Organization> updateRecursionPathColumnOrganization(String inputOrganizationId) {
		try {  
			Map<Object, Object> parentIdMap = new HashMap<Object, Object>();
			parentIdMap.put("parentId", inputOrganizationId);
            List<Organization> list = organizationMapper.selectListByMap(parentIdMap);
            if (null != list && list.size()>0) {  
                for (int i = 0; i < list.size(); i++) {  
                	Organization organization = list.get(i);  
                	// 更新数据
                	Organization parentTemp = organizationMapper.selectByPrimaryKey(organization.getParentId());
                	if(parentTemp != null) {
                		if(StringUtilss.isNotEmpty(parentTemp.getPathIds())) {
                			organization.setPathIds(parentTemp.getPathIds() + "," + parentTemp.getId());
                		} else {
                			organization.setPathIds(parentTemp.getId());
                		}
                		if(StringUtilss.isNotEmpty(parentTemp.getPathCodes())) {
                			organization.setPathCodes(parentTemp.getPathCodes() + "," + parentTemp.getCode());
                		} else {
                			organization.setPathCodes(parentTemp.getCode());
                		}
                		if(StringUtilss.isNotEmpty(parentTemp.getPathNames())) {
                			organization.setPathNames(parentTemp.getPathNames() + "," + parentTemp.getName());
                		} else {
                			organization.setPathNames(parentTemp.getName());
                		}
                		
                	} else {
                		organization.setPathCodes(null);
                		organization.setPathIds(null);
                		organization.setPathNames(null);
                	}
                	organizationMapper.updateByPrimaryKey(organization);
                	updateRecursionPathColumnOrganization(organization.getId());  
                }  
            }  
        } catch (Exception e) {  
            e.printStackTrace();  
            return ResponseVO.validfail(e.getMessage());
        }  
		return ResponseVO.successdata("更新成功");
	}
}
